import { useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useMenuKey } from '@/stores'
import { Menu, Button, message } from 'tdesign-react'
import {
  ViewListIcon, FullscreenExitIcon
} from 'tdesign-icons-react'
import './index.less'

const { MenuItem, SubMenu } = Menu

type PropsType = {
  currentAppRouteKey: string,
  menuList: SideBarMenuListType
}

const SideBar = (props: PropsType) => {

  const navigate = useNavigate()
  const location = useLocation()

  const { menuKey, setMenuKey } = useMenuKey()

  const { menuList = [] } = props

  const getActiveTabFromLocation = () => {
    return location.pathname.split('/')[1] || 'home'
  }

  const [collapsed, setCollapsed] = useState(false)

  const exitOption: SideBarMenuItemType =
  {
    title: '退出',
    icon: <FullscreenExitIcon />,
    value: 'exit',
    isTailNode: true
  }

  useEffect(() => {
    let _menuKey = getActiveTabFromLocation()
    setMenuKey(_menuKey)
  }, [location])


  const onMenuItemChange = (value: any) => {
    if (value == 'exit') {
      // TODO: 退出当前应用
      message.warning('退出当前应用')
      // navigate(`/home`)
    } else {
      setMenuKey(value)
      navigate(`/${value}`)
    }
  }

  const renderTitle = (title: string) => {
    if (!collapsed) {
      return title
    } else {
      return <div className='side-bar-title'>{title}</div>
    }
  }

  const renderMenuItem = (item: SideBarMenuItemType) => {
    const { title = '', value= '', icon = undefined } = item
    return <MenuItem
      key={value}
      value={value}
      icon={icon}
    >{renderTitle(title)}</MenuItem>
  }

  const renderSubMenu = (item: SideBarMenuItemType) => {
    const { title = '', value= '', icon = undefined, children: subMenuList = [] } = item
    return <SubMenu title={title} icon={icon} value={value} key={value}>
      {subMenuList.map((_item: SideBarMenuItemType, index: number) => {
        const { isTailNode = false, title = '', value = '', icon = undefined } = _item
        if (false) console.log(index, title, value, icon)
        return isTailNode ? renderMenuItem(_item) : renderSubMenu(_item)
      })}
    </SubMenu>
  }

  return <div className={'side-bar'}>
    <Menu
      value={menuKey}
      collapsed={collapsed}
      expandMutex={false}
      width={[200, 64]}
      onChange={onMenuItemChange}
      operations={
        <Button variant='text' shape='square' icon={<ViewListIcon />} onClick={() => setCollapsed(!collapsed)} />
      }
      logo={<div className="custom-logo main-logo"></div>}
    >
      {menuList.concat(exitOption).map((item: SideBarMenuItemType, index: number) => {
        const { isTailNode = false, title = '', value = '', icon = undefined } = item
        if (false) console.log(index, title, value, icon)
        return isTailNode ? renderMenuItem(item) : renderSubMenu(item)
      })}
    </Menu>
  </div>
}

export default SideBar
